package com.aiju.cash.ui.good.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiju.bean.Good;
import com.aiju.bean.GoodsType;
import com.aiju.cash.R;
import com.aiju.cash.ui.good.fragment.GoodFragment;
import com.aiju.cash.ui.good.manager.GoodManager;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.aiju.widgit.ShoppingView;
import com.aiju.widgit.dialog.EditWeighDialog;
import com.bumptech.glide.Glide;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;

import java.util.List;

/**
 * @author: 佐为
 * @date: 2016-12-13 10:31
 * @version: V1.0
 * @Description: 商品适配器
 */
public class TeamsAndHeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements StickyRecyclerHeadersAdapter<RecyclerView.ViewHolder>,
        GoodManager.OnChangeListener {

    private int showType;
    private boolean delete;
    private Context mContext;

    private GoodManager goodManager;
    private List<Good> teamList;
    private List<GoodsType> categoryList;

    public void setShowType(int show) {
        this.showType = show;
    }

    public void setDelete(boolean delete) {
        this.delete = delete;
    }

    public TeamsAndHeaderAdapter(Context context, GoodManager goodManager) {
        this.mContext = context;
        this.goodManager = goodManager;
        this.teamList = goodManager.getGoods();
        this.categoryList = goodManager.getGoodsTypes();
    }

    @Override
    public int getItemCount() {
        return teamList.size();
    }

    /**
     * 返回值相同会被默认为同一项
     *
     * @param position
     * @return
     */
    @Override
    public long getHeaderId(int position) {
        return getSortType(position);
    }

    //获取当前球队的类型
    public int getSortType(int position) {
        int sort = -1;
        int sum = 0;
        for (int i = 0; i < categoryList.size(); i++) {
            if (position >= sum) {
                sort++;
            } else {
                return sort;
            }
            sum += categoryList.get(i).getGoodsList().size();
        }
        return sort;
    }

    /**
     * ===================================================================================================
     * header的ViewHolder
     * ===================================================================================================
     */
    @Override
    public HeaderViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.header_team_list, viewGroup, false);
        return new HeaderViewHolder(view);
    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        View view = viewHolder.itemView;
        TextView textView = (TextView) view.findViewById(R.id.tvGoodsItemTitle);
        textView.setText(categoryList.get(getSortType(position)).getName());
    }

    private class HeaderViewHolder extends RecyclerView.ViewHolder {
        public HeaderViewHolder(View itemView) {
            super(itemView);
        }
    }

    /**
     * ==================================================================================================
     * 以下为contentViewHolder
     * ==================================================================================================
     */
    @Override
    public ContentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_team, parent, false);

        return new ContentViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final ContentViewHolder viewHolder = (ContentViewHolder) holder;

        final Good good = teamList.get(position);

        viewHolder.nameTextView.setText(good.getName());
        if (good.isWeighGood()) {
            viewHolder.priceTextView.setText(good.getPrice() + "/" + good.getUnit());
        } else {
            viewHolder.priceTextView.setText(good.getPrice());
        }
        viewHolder.rootView.setSelected(good.isSelect());
        viewHolder.rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(v, position);
                }
            }
        });

        if (showType == GoodFragment.DELETE) {
            if (delete) {
                viewHolder.imageViewDelete.setVisibility(View.VISIBLE);
                viewHolder.shoppingView.setVisibility(View.GONE);
            } else {
                viewHolder.imageViewDelete.setVisibility(View.GONE);
                viewHolder.shoppingView.setVisibility(View.GONE);
            }
        } else if (showType == GoodFragment.SHOP) {
            viewHolder.imageViewDelete.setVisibility(View.GONE);
            viewHolder.shoppingView.setVisibility(View.VISIBLE);
            if (good.isWeighGood()) {
                viewHolder.shoppingView.setShowWeigh(goodManager.getSelectedItemWeighById(good.getIntId()));
                viewHolder.shoppingView.getWeighTextView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new EditWeighDialog(mContext)
                                .setTitileText(good.getName())
                                .setMsgText(good.getPrice() + "/" + good.getUnit())
                                .setContentText(Util.clearZero(good.getWeigh()))
                                .setLayoutParams()
                                .setOnEditClick(new EditWeighDialog.OnEditClick() {
                                    @Override
                                    public void onCancel() {
                                        viewHolder.shoppingView.setSum(0);
                                    }

                                    @Override
                                    public void onSubmit(String msg) {
                                        if (TextUtils.isEmpty(msg)){
                                            T.ToastShort("请输入商品重量");
                                            viewHolder.shoppingView.setSum(0);
                                            return;
                                        }
                                        good.setWeigh(Double.valueOf(msg));
                                        goodManager.update(true);
                                    }
                                })
                                .setCanceledOnTouchOutside(false).show();
                    }
                });
            } else {
                viewHolder.shoppingView.setSum(goodManager.getSelectedItemCountById(good.getIntId()));
            }
            viewHolder.shoppingView.setOnAmountChangeListener(new ShoppingView.OnAmountChangeListener() {
                @Override
                public void onAmountChange(int type, int sum) {
                    if (type == ShoppingView.ADD) {
                        if (good.isWeighGood()) {
                            new EditWeighDialog(mContext)
                                    .setTitileText(good.getName())
                                    .setMsgText(good.getPrice() + "/" + good.getUnit())
                                    .setLayoutParams()
                                    .setOnEditClick(new EditWeighDialog.OnEditClick() {
                                        @Override
                                        public void onCancel() {
                                            viewHolder.shoppingView.setSum(0);
                                        }

                                        @Override
                                        public void onSubmit(String msg) {
                                            if (TextUtils.isEmpty(msg)){
                                                T.ToastShort("请输入商品重量");
                                                viewHolder.shoppingView.setSum(0);
                                                return;
                                            }
                                            good.setWeigh(Double.valueOf(msg));
                                            goodManager.add(good, true);
                                        }
                                    })
                                    .setCanceledOnTouchOutside(false).show();
                        } else {
                            goodManager.add(good, true);
                        }
                    } else {
                        goodManager.remove(good, true);
                    }
                }
            });
        }

        Glide.with(mContext)
                .load(teamList.get(position).getImageUrl())
                .placeholder(R.mipmap.icon_empty)
                .centerCrop()
                .into(viewHolder.imageViewTeam);
    }

    private class ContentViewHolder extends RecyclerView.ViewHolder {
        View rootView;
        TextView nameTextView;
        TextView priceTextView;
        ImageView imageViewTeam;
        ImageView imageViewDelete;
        ShoppingView shoppingView;

        public ContentViewHolder(View itemView) {
            super(itemView);
            rootView = itemView;
            nameTextView = (TextView) itemView.findViewById(R.id.tv_good_name);
            priceTextView = (TextView) itemView.findViewById(R.id.tv_good_price);
            imageViewTeam = (ImageView) itemView.findViewById(R.id.iv_good_pic);
            imageViewDelete = (ImageView) itemView.findViewById(R.id.iv_good_delete);
            shoppingView = (ShoppingView) itemView.findViewById(R.id.shop_num);
        }
    }

    //点击事件
    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    @Override
    public void changeView() {
        notifyDataSetChanged();
    }
}
